import React from 'react';
import { Form, Input, DatePicker, Card, Button, Table, Progress, message } from 'antd';
import { history } from 'umi'
import moment from 'moment';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { Pagination, AdvancedSearch, TableFilter } from '@/components';
import { StartTaskModal, CopyText } from '../../components';
import { useParticipateTaskList } from '../../hooks';
import { checkOperate } from '../../services';
import {
    TaskStepList,
    TaskStepListFilter,
    TaskPriorityList,
    TaskStatus,
    TaskStatusList,
    TaskAction,
    PageFromType,
    toNum
} from '../../utils';
import { showPressModal } from '../containers/MyTaskActionModal';
import { showTipBoxInfoModal } from '../containers/MyTaskInfoModal';
import styles from './MyParticipate.less';

const { RangePicker } = DatePicker;

const MyParticipate = ({ form, location }) => {
    const { getFieldDecorator, getFieldsValue } = form;
    const { query: urlQuery } = location;
    const [query, setQuery] = React.useState({
        taskNo: urlQuery.taskNo || '',
        taskName: urlQuery.taskName || '',
        executeEmployeeName: urlQuery.executeEmployeeName || '',
        planEndTimeStart: urlQuery.planEndTimeStart || '',
        planEndTimeEnd: urlQuery.planEndTimeEnd || '',
        orderByField: urlQuery.orderByField || '',
        pageNo: urlQuery.pageNo || 1,
        pageSize: urlQuery.pageSize || 10,
        taskPriority: toNum(urlQuery.taskPriority),
        taskStep: toNum(urlQuery.taskStep),
        taskStatus: toNum(urlQuery.taskStatus)
    });

    const [taskLoading, taskData, taskTotal] = useParticipateTaskList(query); // 获取任务管理列表
    const [actionLoading, setActionLoading] = React.useState(false);
    const [startModalVisible, setStartModalVisible] = React.useState(false); // 发起任务弹窗显示与否
    const [startModalProps, setStartModalProps] = React.useState(null); // 发起任务弹窗参数

    const routerReplace = newQuery => {
        history.push({
            query: {
                ...urlQuery,
                ...newQuery
            }
        });
        setQuery({
            ...query,
            ...newQuery
        });
    };

    const handlePaginationChange = _pagination => {
        const { current, ...rest } = _pagination;
        routerReplace({
            ...rest,
            pageNo: current
        });
    };

    const handleTableChange = async (pagination, filters, sorter) => {
        const { taskPriority = [], taskStatus = [], taskStep = [] } = filters;
        let orderByField = '';
        if (sorter && sorter.field && sorter.order) {
            orderByField = `${sorter.field}|${sorter.order.replace('end', '')}`;
        }
        routerReplace({
            orderByField,
            taskPriority: taskPriority.length > 0 ? taskPriority[0] : '',
            taskStatus: taskStatus.length > 0 ? taskStatus[0] : '',
            taskStep: taskStep.length > 0 ? taskStep[0] : '',
            pageNo: 1
        });
    };

    const handleStartModalOk = () => {
        // console.log('===============================================>操作成功');
        setQuery({
            ...query
        });
    };

    const handleStartModalCancel = () => {};

    const handleActionClick = (item, record) => async () => {
        if (actionLoading) return;
        setActionLoading(true);
        try {
            const res = await checkOperate(record.id);
            const { code, data } = res;
            if (code === 10000) {
                const {
                    enable,
                    inAuditFlag,
                    auditEmployeeName,
                    inAcceptanceFlag,
                    acceptanceEmployeeName,
                    allAuditNotPassFlag
                } = data;
                if (enable) {
                    setStartModalProps({
                        type: 'new_child_task',
                        record
                    });
                    setStartModalVisible(true);
                    return;
                }
                if (inAuditFlag) {
                    showPressModal({
                        form,
                        title: '新增子任务',
                        taskId: record.id,
                        type: '审核',
                        employeeName: auditEmployeeName
                    });
                    return;
                }
                if (inAcceptanceFlag) {
                    showPressModal({
                        form,
                        title: '新增子任务',
                        taskId: record.id,
                        type: '验收',
                        employeeName: acceptanceEmployeeName
                    });
                    return;
                }
                if (allAuditNotPassFlag) {
                    showTipBoxInfoModal({
                        title: '新增子任务',
                        rows: ['当前任务审核不通过，无法新增子任务', '请变更任务重新审核！']
                    });
                    return;
                }
                return;
            }
            message.error('操作失败！');
        } catch (e) {
            console.error(e);
        } finally {
            setActionLoading(false);
        }
    };

    const extraButtons = (
        <Button
            type="primary"
            onClick={() => {
                setStartModalProps(null);
                setStartModalVisible(true);
            }}
        >
            发起任务
        </Button>
    );

    const defaultSort = type => {
        const { orderByField = '' } = urlQuery;
        const str = orderByField ? orderByField.replace(`${type}|`, '').trim() : '';
        if (str === 'asc') {
            return 'ascend';
        }
        if (str === 'desc') {
            return 'descend';
        }
        return false;
    };

    const renderEllipsis = text => (
        <div style={{ width: '100%', minWidth: 200, position: 'relative' }}>
            <span
                style={{
                    position: 'absolute',
                    left: 0,
                    right: 0,
                    top: 0,
                    transform: 'translateY(-50%)',
                    overflow: 'hidden',
                    whiteSpace: 'nowrap',
                    textOverflow: 'ellipsis'
                }}
                title={text}
            >
                {text}
            </span>
        </div>
    );

    const renderProgress = (text = '0', record) => {
        let format = {};
        let color = '#5AD8A6';
        if (toNum(text) >= 100) {
            format = {
                format: () => '100%'
            };
        }
        if (record.taskStatus === TaskStatus.FINISH || record.taskStatus === TaskStatus.CANCEL) {
            color = '#999999';
        } else if (record.taskStatus === TaskStatus.PAUSE) {
            color = '#FFA784';
        }
        return (
            <Progress
                className={styles.taskProgress}
                percent={Number(text)}
                strokeColor={color}
                size="small"
                {...format}
            />
        );
    };

    const columns = [
        {
            title: '任务编号',
            dataIndex: 'taskNo',
            width: 150,
            render: text => <CopyText text={text} />
        },
        {
            title: '任务名称',
            dataIndex: 'taskName',
            render: text => renderEllipsis(text)
        },
        {
            title: '执行人',
            dataIndex: 'taskExecutor',
            width: 100
        },
        {
            title: '截止时间',
            dataIndex: 'planEndTime',
            width: 120,
            sorter: () => {},
            sortOrder: defaultSort('planEndTime'),
            render: text => {
                if (text) {
                    return text.indexOf('23:59:59') !== -1
                        ? moment(text).format('MM-DD')
                        : moment(text).format('MM-DD HH:mm');
                }
                return '';
            }
        },
        {
            title: '优先级',
            dataIndex: 'taskPriority',
            filters: TaskPriorityList,
            width: 115,
            filteredValue: typeof query.taskPriority === 'number' ? [query.taskPriority] : [],
            filterMultiple: false,
            filterDropdown: filterProps => <TableFilter {...filterProps} />,
            render: text => (TaskPriorityList[text - 1] ? TaskPriorityList[text - 1].text : '')
        },
        {
            title: '环节',
            dataIndex: 'taskStep',
            filters: TaskStepListFilter,
            width: 100,
            filteredValue: typeof query.taskStep === 'number' ? [query.taskStep] : [],
            filterMultiple: false,
            filterDropdown: filterProps => <TableFilter {...filterProps} />,
            render: text => {
                const arr = TaskStepList.filter(item => item.value === text);
                return arr.length > 0 ? arr[0].text : '';
            }
        },
        {
            title: '状态',
            dataIndex: 'taskStatus',
            filters: TaskStatusList,
            width: 100,
            filteredValue: typeof query.taskStatus === 'number' ? [query.taskStatus] : [],
            filterMultiple: false,
            filterDropdown: filterProps => <TableFilter {...filterProps} />,
            render: text => (TaskStatusList[text - 1] ? TaskStatusList[text - 1].text : '')
        },
        {
            title: '当前进度',
            dataIndex: 'taskProgress',
            width: 150,
            render: (text, record) => renderProgress(text, record)
        },
        {
            title: '操作',
            dataIndex: 'action',
            width: 110,
            fixed: 'right',
            className: styles.tableAction,
            onCell: () => ({
                onClick: e => {
                    e.stopPropagation();
                }
            }),
            render: (text, record) => {
                if (record.taskStatus !== TaskStatus.FINISH && record.taskStatus !== TaskStatus.CANCEL) {
                    return (
                        <div className={styles.actionButton}>
                            <span onClick={handleActionClick(TaskAction.COPY, record)}>新增子任务</span>
                        </div>
                    );
                }
                return '';
            }
        }
    ];

    const getParams = () => {
        const param = getFieldsValue();
        const { deadLine = [], ...rest } = param;
        return {
            ...rest,
            planEndTimeStart: deadLine.length > 1 ? deadLine[0].format('YYYY-MM-DD 00:00:00') : '',
            planEndTimeEnd: deadLine.length > 1 ? deadLine[1].format('YYYY-MM-DD 23:59:59') : ''
        };
    };

    const handleSubmit = () => {
        // console.log(getParams());
        routerReplace({
            ...getParams(),
            pageNo: 1
        });
    };

    const handelReset = () => {
        handleSubmit();
    };

    React.useEffect(() => {
        const { taskNo, executeEmployeeName, taskName, planEndTimeStart, planEndTimeEnd } = query;
        form.setFieldsValue({
            taskNo: taskNo || '',
            executeEmployeeName: executeEmployeeName || '',
            taskName: taskName || '',
            deadLine: planEndTimeStart && planEndTimeEnd ? [moment(planEndTimeStart), moment(planEndTimeEnd)] : []
        });
    }, []);

    return (
        <PageHeaderWrapper>
            <Card bordered={false} extra={extraButtons}>
                <AdvancedSearch form={form} onSubmit={handleSubmit} onReset={handelReset}>
                    <Form.Item label="任务编号">
                        {getFieldDecorator('taskNo', {
                            initialValue: ''
                        })(<Input placeholder="请输入任务编号" allowClear />)}
                    </Form.Item>
                    <Form.Item label="任务名称">
                        {getFieldDecorator('taskName', {
                            initialValue: ''
                        })(<Input placeholder="请输入任务名称" allowClear />)}
                    </Form.Item>
                    <Form.Item label="执行人">
                        {getFieldDecorator('executeEmployeeName', {
                            initialValue: ''
                        })(<Input placeholder="请输入执行人" allowClear />)}
                    </Form.Item>
                    <Form.Item label="截止时间">
                        {getFieldDecorator('deadLine', {
                            initialValue: []
                        })(
                            <RangePicker
                                dropdownClassName={styles.rangePicker}
                                ranges={{
                                    本周: [moment().startOf('week'), moment().endOf('week')],
                                    本月: [moment().startOf('month'), moment().endOf('month')],
                                    本季度: [moment().startOf('quarter'), moment().endOf('quarter')]
                                }}
                            />
                        )}
                    </Form.Item>
                </AdvancedSearch>
                <Table
                    rowKey="id"
                    rowClassName={styles.tableRow}
                    bordered={false}
                    columns={columns}
                    loading={taskLoading || actionLoading}
                    dataSource={taskData}
                    onChange={handleTableChange}
                    pagination={false}
                    scroll={{ x: 'max-content' }}
                    onRow={record => ({
                        onClick: () => {
                            history.push({
                                pathname: '/work/task/taskdetail',
                                query: { id: record.id || '', type: PageFromType.PARTICIPATE },
                                state: { tabRoute: true, tabRefresh: true }
                            });
                        }
                    })}
                />
                <Pagination
                    total={taskTotal}
                    current={Number(query.pageNo)}
                    pageSize={Number(query.pageSize)}
                    onChange={handlePaginationChange}
                    loading={taskLoading || actionLoading}
                />
                <StartTaskModal
                    visible={startModalVisible}
                    setVisible={setStartModalVisible}
                    onOk={handleStartModalOk}
                    onCancel={handleStartModalCancel}
                    {...startModalProps}
                />
            </Card>
        </PageHeaderWrapper>
    );
};

export default Form.create()(MyParticipate);
